@tool
extends Control
class_name EmulatorOverlay

@export var frame_texture: Texture2D
@export var device_size: Vector2i = Vector2i(1080, 2400)

var _touch_pressed := false

func _ready() -> void:
	mouse_filter = MOUSE_FILTER_STOP
	set_anchors_preset(Control.PRESET_FULL_RECT)
	set_deferred("size", get_viewport().size)
	if frame_texture != null:
		var texrect := TextureRect.new()
		texrect.texture = frame_texture
		texrect.stretch_mode = TextureRect.STRETCH_KEEP_ASPECT_COVERED
		texrect.size_flags_horizontal = Control.SIZE_EXPAND_FILL
		texrect.size_flags_vertical = Control.SIZE_EXPAND_FILL
		texrect.set_anchors_preset(Control.PRESET_FULL_RECT)
		texrect.modulate = Color(1, 1, 1, 1.0)
		add_child(texrect)
	queue_redraw()

func _draw() -> void:
	if frame_texture == null:
		var margin := 24.0
		var color := Color(0, 0, 0, 0.85)
		# Top and bottom bars
		draw_rect(Rect2(Vector2(0, 0), Vector2(size.x, margin)), color, true)
		draw_rect(Rect2(Vector2(0, size.y - margin), Vector2(size.x, margin)), color, true)
		# Left and right bars
		draw_rect(Rect2(Vector2(0, 0), Vector2(margin, size.y)), color, true)
		draw_rect(Rect2(Vector2(size.x - margin, 0), Vector2(margin, size.y)), color, true)
		# Simple speaker notch
		var speaker_w := 80.0
		draw_rect(Rect2(Vector2(size.x * 0.5 - speaker_w * 0.5, margin * 0.25), Vector2(speaker_w, margin * 0.5)), color.lightened(0.1), true)

func _gui_input(event: InputEvent) -> void:
	if event is InputEventMouseButton:
		var t := InputEventScreenTouch.new()
		t.index = 0
		t.position = (event as InputEventMouseButton).position
		t.pressed = (event as InputEventMouseButton).pressed
		Input.parse_input_event(t)
		_touch_pressed = (event as InputEventMouseButton).pressed
	elif event is InputEventMouseMotion and _touch_pressed:
		var d := InputEventScreenDrag.new()
		d.index = 0
		d.position = (event as InputEventMouseMotion).position
		d.relative = (event as InputEventMouseMotion).relative
		Input.parse_input_event(d)